package com.gw.vip.server.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gw.vip.server.po.BatchClearLedger;
import com.gw.vip.server.po.Account;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author GW
 * @description
 * @since 2022-05-03
 */
public interface AccountMapper extends BaseMapper<Account> {

    /**
     * 帐户变动
     * @param accountId
     * @param amt
     * @return
     */
    @Update("UPDATE account SET amt = amt + #{amt}, upd_time=NOW() WHERE id = #{accountId} AND amt + #{amt}>=0 AND amt + #{amt}-lock_amt>=0")
    int updateAmt(String accountId, BigDecimal amt);

    /**
     * 帐户变动
     * @param accountId
     * @param updAmt
     * @return
     */
    @Update("UPDATE account SET lock_amt = lock_amt + #{updAmt}, upd_time=NOW() WHERE id = #{accountId} AND lock_amt + #{updAmt}>=0 AND amt - #{updAmt}-lock_amt>=0")
    int updateLockAmt(String accountId, BigDecimal updAmt);

    /**
     * 根据id更新清算金额
     * @param accountId
     * @return
     */
    @Update("UPDATE account SET clear_amt = amt WHERE id = #{accountId}")
    int updateClearAmt(String accountId);

    /**
     * 获取用户可用余额
     * @param userId
     * @return
     */
    @Select("SELECT sum(amt-lock_amt) FROM account WHERE user_id=#{userId} AND status='S'")
    BigDecimal getAvaBal(String userId);

    /**
     * 获取卡号可用余额
     * @param pan
     * @return
     */
    @Select("SELECT sum(amt-lock_amt) FROM account WHERE pan=#{pan} AND status='S'")
    BigDecimal getAvaBalByPan(String pan);

    /**
     * 获取金额变动帐户
     * @return
     */
    @Select("SELECT * FROM account WHERE last_amt<>clear_amt")
    List<Account> listByChange();

    /**
     * 获取当前清算日期总账
     * @return
     */
    @Select("SELECT capital_id, SUM(clear_amt) amt FROM account GROUP BY capital_id")
    List<BatchClearLedger> getLedger();

    /**
     * 查询所有上日余额跟当前金额不一致的帐户
     * @return
     */
    @Select("SELECT * FROM account WHERE last_amt<>clear_amt")
    List<Account> listByLast();

    /**
     * 更新上日余额
     * @param id
     * @return
     */
    @Update("UPDATE account SET last_amt=clear_amt, upd_time=NOW() WHERE id=#{id}")
    int updateLastAmt(String id);

    /**
     * 查询出所有清算金额和当前金额不一致的帐户
     * @return
     */
    @Select("SELECT * FROM account WHERE amt<>clear_amt")
    List<Account> listByClearReady();

    /**
     * 查找可以扣款的主账户
     * @param userId
     * @return
     */
    @Select("SELECT * FROM account WHERE user_id=#{userId} AND acc_type='main' AND status='S' AND amt-lock_amt>0")
    List<Account> mainAvaAcc(String userId);

    /**
     * 根据卡号查找可以扣款的账号
     * @param pan
     * @return
     */
    @Select("SELECT * FROM account WHERE pan=#{pan} AND status='S' AND amt-lock_amt>0")
    List<Account> avaAccByPan(String pan);
}
